package com.taobao.chenbao.template.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.taobao.chenbao.template.biz.ExampleBiz;
import com.taobao.chenbao.template.biz.ImportBiz;
import com.taobao.chenbao.template.entity.Student;
import com.taobao.chenbao.template.entity.StudentCourses;
import com.taobao.chenbao.template.entity.Teacher;
import com.taobao.chenbao.template.entity.UserAdmin;
import com.taobao.chenbao.template.mapper.StudentCoursesMapper;
import com.taobao.chenbao.template.mapper.StudentMapper;
import com.taobao.chenbao.template.mapper.TeacherMapper;
import com.taobao.chenbao.template.mapper.UserAdminMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    StudentCoursesMapper studentCoursesMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    TeacherMapper teacherMapper;
    @Autowired
    UserAdminMapper userAdminMapper;
    @Autowired
    ImportBiz importBiz;

    @GetMapping("/getStdCourses")
    public List<StudentCourses> getStudentCourses(long studentId) {
        Example example = ExampleBiz.getExample(StudentCourses.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("student_id", studentId);
        return studentCoursesMapper.selectByExample(example);
    }

    @GetMapping("/toselectstudent")
    public String toselectstudent(HttpServletRequest request, HttpSession session) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>当前没登录</h1>";
        }
        if ("teacher".equals(role)) {
            Teacher teacher = (Teacher) object;
            Example example = ExampleBiz.getExample(StudentCourses.class);
            example.createCriteria().andEqualTo("teacher_id", teacher.getId()).andEqualTo("selected", "已选择");
            List<StudentCourses> studentCourses = studentCoursesMapper.selectByExample(example);
            if (studentCourses.size() > teacher.getStudentNumber()) {
                return "<h1>选择的数量已到上线，无法再选择</h1>";
            }
            Example example1 = ExampleBiz.getExample(StudentCourses.class);
            example1.createCriteria().andEqualTo("teacher_id", teacher.getId()).andEqualTo("selected", "未选择");
            studentCourses = studentCoursesMapper.selectByExample(example1);
            request.setAttribute("list", studentCourses);
        }
        return "selectstudent";
    }

    @PostMapping("/selectstudent")
    @ResponseBody
    public String selectstudent(HttpSession session, HttpServletResponse response) {
        return "<h1>志愿填报失败</h1>";
    }

    @PostMapping("/select")
    @ResponseBody
    public void select(String id, HttpSession session, HttpServletResponse response) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return;
        }
        if ("teacher".equals(role)) {
            Teacher teacher = (Teacher) object;
            Example example = ExampleBiz.getExample(StudentCourses.class);
            example.createCriteria().andEqualTo("id", id);
            List<StudentCourses> studentCourses = studentCoursesMapper.selectByExample(example);
            if (!studentCourses.isEmpty()) {
                StudentCourses studentCourse = studentCourses.get(0);
                studentCourse.setSelected("已选择");
                studentCoursesMapper.updateByPrimaryKeySelective(studentCourse);
            }
        }
    }

    @GetMapping("/toFill")
    public String toFill(HttpServletRequest request) {
        return "fill";
    }

    @PostMapping("fill")
    @ResponseBody
    public String fill(String first, String second, String three, HttpSession session, HttpServletResponse response) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>志愿填报失败</h1>";

        }

        if ("student".equals(role)) {
            Student student = (Student) object;
            StudentCourses firstCourse = new StudentCourses();
            firstCourse.setStudent_id(student.getId());
            firstCourse.setStudent_name(student.getName());
            firstCourse.setTeacher_id(Long.valueOf(first));
            //根据id查询教师名称
            Example example = ExampleBiz.getExample(Teacher.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id", first);
            List<Teacher> teachers = teacherMapper.selectByExample(example);
            if (teachers.isEmpty()) {
                return "<h1>志愿1的老师不存在，请重新填写</h1>";
            }
            firstCourse.setTeacher_name(teachers.get(0).getName());
            firstCourse.setZhiyuanlevel(1L);
            firstCourse.setSelected("未选择");

            StudentCourses secondCourse = new StudentCourses();
            secondCourse.setStudent_id(student.getId());
            secondCourse.setStudent_name(student.getName());
            secondCourse.setTeacher_id(Long.valueOf(second));
            //根据id查询教师名称
            Example example1 = ExampleBiz.getExample(Teacher.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("id", second);
            List<Teacher> teachers1 = teacherMapper.selectByExample(example1);
            if (teachers1.isEmpty()) {
                return "<h1>志愿2的老师不存在，请重新填写</h1>";
            }
            secondCourse.setTeacher_name(teachers1.get(0).getName());
            secondCourse.setZhiyuanlevel(2L);
            secondCourse.setSelected("未选择");


            StudentCourses threeCourse = new StudentCourses();
            threeCourse.setStudent_id(student.getId());
            threeCourse.setStudent_name(student.getName());
            threeCourse.setTeacher_id(Long.valueOf(three));
            //根据id查询教师名称
            Example example2 = ExampleBiz.getExample(Teacher.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("id", three);
            List<Teacher> teachers2 = teacherMapper.selectByExample(example2);
            if (teachers2.isEmpty()) {
                return "<h1>志愿3的老师不存在，请重新填写</h1>";
            }
            threeCourse.setTeacher_name(teachers2.get(0).getName());
            threeCourse.setZhiyuanlevel(3L);
            threeCourse.setSelected("未选择");

            studentCoursesMapper.insert(firstCourse);
            studentCoursesMapper.insert(secondCourse);
            studentCoursesMapper.insert(threeCourse);

            return "<h1>志愿填报完成</h1>";
        }
        return "<h1>志愿填报完成</h1>";
    }

    @GetMapping("/toLook")
    public String toLook(HttpServletRequest request, HttpSession session) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>查看最终志愿失败</h1>";
        }
        if ("student".equals(role)) {
            Student student = (Student) object;
            Example example = ExampleBiz.getExample(StudentCourses.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("student_id", student.getId()).andEqualTo("selected","已选择");
            List<StudentCourses> studentCourses = studentCoursesMapper.selectByExample(example);
            if(studentCourses.size()>0){
                request.setAttribute("studentCourse", studentCourses.get(0));
                return "look";
            }
        }
        return "<h1>还没有导师选择，请稍等</h1>";


    }

    @GetMapping("/studentinfo")
    public String studentinfo(HttpServletRequest request) {
        return "studentinfo";
    }

    @GetMapping("tomodifystudent")
    public String tomodifystudent(String id,HttpServletRequest request) {
        request.setAttribute("id",id);
        return "modifystudentinfo";
    }


    @GetMapping("/modifystudentinfo")
    public String modifystudentinfo(HttpServletRequest request) {
        return "modifystudentinfo";
    }

    @PostMapping("modifyStudent")
    @ResponseBody
    public String modifyStudent(String id,String major, String sex, HttpSession session, HttpServletResponse response) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>修改失败</h1>";
        }

        if ("student".equals(role)) {
            Student student = (Student) object;
            student.setMajor(major);
            student.setSex(sex);
            studentMapper.updateByPrimaryKeySelective(student);
            return "<h1>修改成功</h1>";
        }else{
            Example example = ExampleBiz.getExample(Student.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id",id);
            List<Student> students = studentMapper.selectByExample(example);
            if(!students.isEmpty()){
                Student student=students.get(0);
                student.setSex(sex);
                student.setMajor(major);
                studentMapper.updateByPrimaryKeySelective(student);
            }
        }
        return "<h1>修改成功</h1>";
    }

    @PostMapping("modifyTeacher")
    @ResponseBody
    public String modifyTeacher(String id,String studentNumber,HttpSession session, HttpServletResponse response) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>修改失败</h1>";
        }

            Example example = ExampleBiz.getExample(Teacher.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id",id);
            List<Teacher> teachers = teacherMapper.selectByExample(example);
            if(!teachers.isEmpty()){
                Teacher teacher=teachers.get(0);
                teacher.setStudentNumber(Long.valueOf(studentNumber));
                teacherMapper.updateByPrimaryKeySelective(teacher);
            }
        return "<h1>修改成功</h1>";
    }



    @GetMapping("/teacherinfo")
    public String getTeacherInfo(HttpServletRequest request) {
        return "teacherinfo";
    }

    @GetMapping("/studentcourses")
    public String getStudentCourses() {
        return "studentcourses";
    }

    @GetMapping("/changepwd")
    public String changePwd() {
        return "changepwd";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login";
    }

    @PostMapping("changePassword")
    @ResponseBody
    public String changePassWord(String newPassword, HttpSession session, HttpServletResponse response) throws IOException {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            //   return "login";
            return "<h1>修改失败</h1>";

        }

        if ("student".equals(role)) {
            Student student = (Student) object;
            student.setPassword(newPassword);
            studentMapper.updateByPrimaryKeySelective(student);
            return "<h1>修改成功</h1>";
        }
        return "<h1>修改成功</h1>";
    }


    @PostMapping("/batch")
    public void batchChange(@RequestParam("file") MultipartFile file, @RequestParam("role") String role, HttpServletRequest request) throws Exception {
        if ("teachet".equals(role)) {
            ExcelImportResult<Teacher> excelImportResult = importBiz.getDatas(file, (Class) Teacher.class);
            List<Teacher> teachers = excelImportResult.getList();
            teachers.forEach(teacher -> teacherMapper.insert(teacher));
        }
        if ("student".equals(role)) {
            ExcelImportResult<Student> excelImportResult = importBiz.getDatas(file, (Class) Student.class);
            List<Student> students = excelImportResult.getList();
            students.forEach(student -> studentMapper.insert(student));
        }
        if ("userAdmin".equals(role)) {
            ExcelImportResult<UserAdmin> excelImportResult = importBiz.getDatas(file, (Class) UserAdmin.class);
            List<UserAdmin> userAdmins = excelImportResult.getList();
            userAdmins.forEach(userAdmin -> userAdminMapper.insert(userAdmin));
        }
    }


    @PostMapping("/importTeacher")
    public void importTeacher(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        ExcelImportResult<Teacher> excelImportResult = importBiz.getDatas(file, (Class) Teacher.class);
        List<Teacher> teachers = excelImportResult.getList();
        teachers.forEach(teacher -> teacherMapper.insert(teacher));
    }

    @PostMapping("/importStudent")
    public void importStudent(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        ExcelImportResult<Student> excelImportResult = importBiz.getDatas(file, (Class) Student.class);
        List<Student> students = excelImportResult.getList();
        students.forEach(student -> studentMapper.insert(student));
    }

    @PostMapping("/importcollegeadmin")
    public void importcollegeadmin(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        ExcelImportResult<UserAdmin> excelImportResult = importBiz.getDatas(file, (Class) UserAdmin.class);
        List<UserAdmin> userAdmins = excelImportResult.getList();
        userAdmins.forEach(userAdmin -> userAdminMapper.insert(userAdmin));
    }


    @GetMapping("/toimportteacher")
    public String toimportteacher() {
        return "importteacher";
    }

    @GetMapping("/toimportstudent")
    public String toimportstudent() {
        return "importstudent";
    }

    @GetMapping("/toimportcolledgeAdmin")
    public String toimportcolledgeAdmin() {
        return "importcolledgeAdmin";
    }

    @GetMapping("/toimportcollegeadmin")
    public String toimportcollegeadmin() {
        return "importcollegeadmin";
    }


    @GetMapping("/querystudent")
    public String querystudent(HttpServletRequest request, HttpSession session) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>当前没登录</h1>";
        }
        if ("collegeAdmin".equals(role)||"researchAdmin".equals(role)) {
            UserAdmin collegeAdmin = (UserAdmin) object;
            Example example = ExampleBiz.getExample(Student.class);
            example.createCriteria();
            List<Student> students = studentMapper.selectByExample(example);

            request.setAttribute("list", students);
        }
        return "querystudent";
    }
    @GetMapping("/querycollegeAdmin")
    public String querycollegeAdmin(HttpServletRequest request, HttpSession session) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>当前没登录</h1>";
        }
        if ("researchAdmin".equals(role)) {
            UserAdmin collegeAdmin = (UserAdmin) object;
            Example example = ExampleBiz.getExample(UserAdmin.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("role","collegeAdmin");
            List<UserAdmin> userAdmins = userAdminMapper.selectByExample(example);

            request.setAttribute("list", userAdmins);
        }
        return "querycollegeAdmin";

    }

    @GetMapping("/queryteacher")
    public String queryteacher(HttpServletRequest request, HttpSession session) {
        String role = (String) session.getAttribute("role");
        Object object = session.getAttribute("userinfo");
        if (StringUtils.isEmpty(role) || Objects.isNull(object)) {
            return "<h1>当前没登录</h1>";
        }
        if ("collegeAdmin".equals(role)||"researchAdmin".equals(role)) {
            Example example = ExampleBiz.getExample(Teacher.class);
            example.createCriteria();
            List<Teacher> teachers = teacherMapper.selectByExample(example);

            request.setAttribute("list", teachers);
        }
        return "queryteacher";
    }
    @GetMapping("/toexport")
    public String toexportcourse() {
        return "exportcourse";
    }

    @GetMapping("/exportcourse")
    @ResponseBody
    public String exportcourse(HttpServletRequest request, HttpSession session) throws Exception {
        List<StudentCourses> studentCourses = studentCoursesMapper.selectAll();
        return importBiz.export(studentCourses, (Class) StudentCourses.class);
    }

}
